import aioredis
from app.config import get_settings

class RedisUtil:
    """
    Redis相关方法
    """

    @classmethod
    async def create_redis_pool(cls) :
        """
        应用启动时初始化redis连接
        :return: Redis连接对象
        """
        settings = get_settings()

        redis = aioredis.ConnectionPool.from_url(
            url=f"redis://{settings.redis_host}",
            port=settings.redis_port,
            password=settings.redis_pwd,
            db=settings.redis_db,
            encoding="utf-8",
            decode_responses=True
        )
        return redis

    @classmethod
    async def close_redis_pool(cls, app):
        """
        应用关闭时关闭redis连接
        :param app: fastapi对象
        :return:
        """
        pass

    @classmethod
    async def get_data(cls, app, key):
        async with aioredis.Redis(connection_pool=app.state.redis_pool) as redis:
            return await redis.get(key)
    

    @classmethod
    async def set_data(cls, app, key, value):
        async with aioredis.Redis(connection_pool=app.state.redis_pool) as redis:
            return await redis.set(key, value)



